import React, { useState, useEffect } from "react";
import style from "../../../scss/index.module.scss";
import Buttons from "../../../componet/Button/button";
import Input from "../../../componet/Input/InputComponent";
import PageSize from "../../../componet/PageSize/PageSize";
import axios from "../../../axios";
import { useDispatch } from "react-redux";
import { getshow } from "../../../store/modules/module";
import { message, Button, Modal } from "antd";

import { importsExcel, exportsExcel } from "../../../until/excel";

export default function PartyMemberManagement(props: {
  setShow: (show: boolean) => void;
  setShow2: (show2: boolean) => void;
  setShow3: (show3: boolean) => void;
}) {
  const [list, setList] = useState<any>([]);
  const [type, setType] = useState<any>([]);
  const [name, setName] = useState("");
  const [organization, setOrganization] = useState("A区域党支部");

  const dispatch = useDispatch();

  const [isModalOpen, setIsModalOpen] = useState(false);

  const showModal = () => {
    setIsModalOpen(true);
  };

  const handleOk = () => {
    setIsModalOpen(false);
  };

  const handleCancel = () => {
    setIsModalOpen(false);
  };

  const getlist = async () => {
    let res: any = await axios.get("http://localhost:3000/dygl", {
      params: {
        name: name,
        organization: organization,
      },
    });
    setList(res.list);
    setType(res.typelist);
  };

  const times = (time: any) => {
    let date = new Date(time);
    let Y = date.getFullYear() + "-";
    let M =
      (date.getMonth() + 1 < 10
        ? "0" + (date.getMonth() + 1)
        : date.getMonth() + 1) + "-";
    let D = date.getDate() + " ";
    return Y + M + D;
  };

  const tels = (tel: any) => {
    let reg = /(\d{3})\d{4}(\d{4})/;
    return tel.replace(reg, "$1****$2");
  };

  const sou = () => {
    getlist();
  };

  const del = async (id: any) => {
    let res = await axios.delete("http://localhost:3000/dygldel?id=" + id);
    if (res.data.code === 241) {
      message.success("删除成功");
      getlist();
    } else {
      message.error("删除失败");
    }
  };

  //批量导入
  const pldr = () => {
    console.log("批量导入");
  };

  //模版下载
  function downloadFile(data: any, fileName: string, fileType: any) {
    // 创建一个Blob对象，表示二进制数据
    const blob = new Blob([data], { type: fileType });

    // 创建一个虚拟链接
    const a = document.createElement("a");
    a.href = URL.createObjectURL(blob);

    // 设置下载文件的名称
    a.download = fileName;

    // 将虚拟链接添加到文档中
    document.body.appendChild(a);

    // 模拟点击链接以触发下载
    a.click();

    // 移除虚拟链接
    document.body.removeChild(a);
  }
  const mbxz = () => {
    let lists = JSON.stringify(list);
    downloadFile(
      lists,
      "党员管理模板.xlsx",
      "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
    );
  };

  //批量导出
  const pldc = () => {
    console.log("批量导出");
  };

  //批量删除
  const changeflag = (item: any) => {
    let idx = list.findIndex((i: any) => i._id === item._id);
    if (item.flag === true) {
      item.flag = false;
    } else {
      item.flag = true;
    }
    list[idx] = item;
    setList(list);
  };
  const plsc = async () => {
    let ids = list
      .filter((item: any) => item.flag === true)
      .map((i: any) => i._id)
      .join(",");
    let res = await axios.delete("http://localhost:3000/dygldels?ids=" + ids);
    if (res.data.code === 243) {
      message.success("删除成功");
      getlist();
    } else {
      message.error("删除失败");
    }
  };

  useEffect(() => {
    getlist();
    //把list写入数据库
    if (list.length > 0) {
      //写入数据库
      // axios.post("http://localhost:3000/dygllist", list).then((res) => {
      //   console.log(res.data);
      // });
    }
  }, []);
  return (
    <div>
      <div className={style.mxkdygltop}>
        <Buttons
          text={"新增"}
          setColor="white"
          onClick={() => {
            props.setShow(false);
            props.setShow2(true);
            props.setShow3(false);
          }}
        ></Buttons>
        <Buttons
          text={"批量导入"}
          setColor="white"
          onClick={showModal}
        ></Buttons>
        <Modal
          title="Basic Modal"
          open={isModalOpen}
          onOk={handleOk}
          onCancel={handleCancel}
        >
          <div>
            <input
              type="file"
              accept=".xls,.xlsx"
              multiple={true}
              onChange={(e) => {
                console.log(e);

                // importsExcel(e).then((res) => {
                //   console.log(res);
                // });
              }}
            />
          </div>
        </Modal>
        <Buttons
          text={"模版下载"}
          setColor="white"
          onClick={() => {
            mbxz();
          }}
        ></Buttons>
        <Buttons
          text={"批量导出"}
          setColor="white"
          onClick={() => {
            pldc();
          }}
        ></Buttons>
        <Buttons
          text={"批量删除"}
          setColor="white"
          onClick={() => {
            plsc();
          }}
        ></Buttons>
        姓名:
        <Input
          value={name}
          onChange={(e) => {
            setName(e);
          }}
        ></Input>
        <Buttons
          text={"查询"}
          setColor="white"
          setBackgroundColor="rgb(204, 53, 47)"
          onClick={() => {
            getlist();
          }}
        ></Buttons>
        <Buttons
          text={"重置"}
          setBackgroundColor="white"
          onClick={() => {
            setName("");
          }}
        ></Buttons>
      </div>
      <div className={style.mxkbox}>
        <div className={style.mxkboxleft}>
          <div className={style.mxkboxlefttop}>
            <span>党组织结构</span>
          </div>
          {type.map((item: any, index: any) => {
            return (
              <div
                className={style.mxkboxlefttype}
                key={index}
                onClick={() => {
                  setOrganization(item);
                  sou();
                }}
              >
                <span>{item}</span>
              </div>
            );
          })}
        </div>
        <div className={style.mxkboxright}>
          <table className={style.mxkdygltable}>
            <thead>
              <tr>
                <th>
                  <input type="checkbox" />
                </th>
                <th>组织</th>
                <th>姓名</th>
                <th>人员类型</th>
                <th>性别</th>
                <th>联系电话</th>
                <th>党内职务</th>
                <th>转为预备党员日期</th>
                <th>转为正式党员日期</th>
                <th>操作</th>
              </tr>
            </thead>
            <tbody>
              {list.map((item: any, index: number) => {
                return (
                  <tr key={index}>
                    <td>
                      <input
                        type="checkbox"
                        value={item.flag}
                        onChange={() => {
                          changeflag(item);
                        }}
                      />
                    </td>
                    <td>{item.organization}</td>
                    <td>{item.name}</td>
                    <td>{item.type}</td>
                    <td>{item.gender}</td>
                    <td>{tels(item.phone)}</td>
                    <td>{item.party_post}</td>
                    <td>{times(item.probationary_date)}</td>
                    <td>{times(item.full_membership_date)}</td>
                    <td className={style.bj}>
                      <span
                        className={style.mxkcz}
                        onClick={() => {
                          dispatch(getshow(item));
                          props.setShow(false);
                          props.setShow2(false);
                          props.setShow3(true);
                        }}
                      >
                        编辑
                      </span>
                      <span
                        className={style.mxkcz}
                        onClick={() => {
                          del(item._id);
                        }}
                      >
                        删除
                      </span>
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}
